import React, { useEffect, useState } from 'react';

// @ts-ignore
export function LoginPage({ onLoginSuccess }) {
    const [qrCodeSrc, setQrCodeSrc] = useState('./images/placeholder.png');
    const [ticket, setTicket] = useState<string | null>(null);
    const apiHostUrl = process.env.API_HOST_URL ? process.env.API_HOST_URL : "http://117.72.71.221:8091";
    useEffect(() => {
        // 获取二维码 ticket
        fetch(`${apiHostUrl}/api/v1/login/weixin_qrcode_ticket`)
            .then(response => response.json())
            .then(data => {
                if (data.code === "0000") {
                    const ticket = data.data;
                    setTicket(ticket);
                    setQrCodeSrc(`http://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${ticket}`);
                } else {
                    console.error('获取二维码 ticket 失败:', data.info);
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
    }, []);

    useEffect(() => {
        if (ticket) {
            // 开始轮询检查登录状态
            const intervalId = setInterval(() => {
                checkLoginStatus(ticket, intervalId);
            }, 3000); // 每3秒检查一次

            return () => clearInterval(intervalId); // 清理定时器
        }
    }, [ticket]);

    const checkLoginStatus = (ticket: string, intervalId: NodeJS.Timeout) => {
        fetch(`${apiHostUrl}/api/v1/login/check_login?ticket=${ticket}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === "0000") {
                    console.info("登录成功");
                    // 停止轮询
                    clearInterval(intervalId);
                    // 保存登录 token 到 cookie，设置有效期为30天
                    // setCookie('loginToken', data.data, 30);

                    // 在这里可以重定向到登录后的页面
                    onLoginSuccess(); // 通知 Home 组件登录成功

                    // 检查当前 URL 是否已经符合预期
                    const currentUrl = window.location.href;
                    if (currentUrl.search("userId") && currentUrl.search("activityId")) {

                        setCookie('userId', currentUrl.search("userId"), 30);
                    }
                    const userId = "user_"+new Date().getTime();
                    // sessionStorage.setItem("userId", userId);
                    setCookie('userId', userId, 30);
                     window.location.href = '/?userId='+userId+'&activityId=100301';
                } else {
                    console.info("登录等待中");
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
            });
    };

    const setCookie = (name: string, value: any, days: number) => {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = `${name}=${value};${expires};path=/`;
    };

    return (
        <div className="login-container">
            <span className="title">大营销抽奖平台登录页</span>
            <div className="qr-code">
                <img id="qr-code-img" src={qrCodeSrc} alt="微信二维码" />
            </div>
            <p className="instructions">请使用微信扫描二维码登录</p>
            <style jsx>{`
        body {
          font-family: Arial, sans-serif;
          background-color: #f5f5f5;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
          margin: 0;
        }
        .login-container {
          background-color: #fff;
          padding: 20px;
          border-radius: 10px;
          box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
          text-align: center;
          max-width: 400px;
          width: 100%;
        }
        .login-container h1 {
          margin-bottom: 20px;
          color: #333;
        }
        .qr-code {
          margin: 20px 0;
        }
        .qr-code img {
            margin-left: 80px;
          width: 200px;
          height: 200px;
        }
        .instructions {
          color: #666;
          font-size: 14px;
        }
        .title{
            font-size: 25px;
        }
      `}</style>
        </div>
    );
};